package cc.rengu.igas.mcps.core.service.trans.cardpay;
/*
 * 银行卡余额查询
 *create by zhangbin on 2020/03
 * */

import cc.rengu.igas.channel.cups.common.constant.CupsConfigConstant;
import cc.rengu.igas.channel.cups.facade.bean.CupsTermInfo;
import cc.rengu.igas.channel.cups.facade.request.AcctBalanceQueryRequest;
import cc.rengu.igas.channel.cups.facade.response.AcctBalanceQueryResponse;
import cc.rengu.igas.mcps.common.constant.McpsParamConstant;
import cc.rengu.igas.mcps.common.constant.McpsTreeNodeConstant;
import cc.rengu.igas.mcps.common.enums.McpsAcctTypeEnum;
import cc.rengu.igas.mcps.common.enums.RespCodeEnum;
import cc.rengu.igas.mcps.core.model.AcctAndFeeType;
import cc.rengu.igas.mcps.core.realize.PosParamDealService;
import cc.rengu.igas.mcps.core.realize.impl.PosParamDealServiceImpl;
import cc.rengu.igas.mcps.core.service.base.QuerySevice;
import cc.rengu.igas.mcps.facade.bean.BalanceInfo;
import cc.rengu.igas.mcps.facade.request.PosAcctBalanceQueryRequest;
import cc.rengu.igas.mcps.facade.response.PosAcctBalanceQueryResponse;
import cc.rengu.igas.share.core.model.MchntInfo;
import cc.rengu.igas.share.core.model.MchntTermInfo;
import cc.rengu.igas.share.core.realize.MchntService;
import cc.rengu.igas.share.core.realize.impl.MchntServiceImpl;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.utility.util.*;
import com.alibaba.fastjson.JSON;

public class PosCardAcctBalanceQueryService extends QuerySevice {
    @Override
    protected Object bizBeforeCust() throws Exception {
        PosAcctBalanceQueryRequest posAcctBalanceQueryRequest = new PosAcctBalanceQueryRequest();
        ConvertUtil.convertOutput(posAcctBalanceQueryRequest);
        return posAcctBalanceQueryRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        BizResponse bizResponse = new BizResponse();
        /*初始化报文request*/
        PosAcctBalanceQueryRequest posAcctBalanceQueryRequest = (PosAcctBalanceQueryRequest) request;
        /*初始化返回报文response*/
        PosAcctBalanceQueryResponse posAcctBalanceQueryResponse = new PosAcctBalanceQueryResponse();
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        /*初始化余额 渠道流水号 ic卡数据域*/
        String balance = "";
        /*获取商户号*/
        String mchntNo = posAcctBalanceQueryRequest.getMchntNo();
        /*获取终端号*/
        String termNo = posAcctBalanceQueryRequest.getTermNo();
        /*获取机构号*/
        String instId = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.INST_ID);
        /* 获取交易码*/
        String txnNum = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TXN_NUM);
        /*获取系统流水号*/
        String sysNum = xmlTreeUtil.getXmlTreeStringValue(McpsTreeNodeConstant.SYS_SEQ_NUM);
        //获取卡BIN信息并判断是否支持此类卡的渠道交易
        /*获取卡号*/
        String cardNo = posAcctBalanceQueryRequest.getPayAcctNo();
        /* 获取终端信息 */
        MchntService mchntService = new MchntServiceImpl();
        MchntTermInfo mchntTermInfo = mchntService.getMchntTermInfo(instId, mchntNo, termNo);
        /*校验 是否支持此类卡进行交易 并获取账户类型与费率类型*/
        PosParamDealService posParamDealService = new PosParamDealServiceImpl();
        AcctAndFeeType acctAndFeeType = posParamDealService.judgeOwnOtherBank(instId, cardNo, txnInfo.getSrcTxnAuthCfg().getSupportAcctType());
        /*初始化转pin后的值*/
        String newPin;
        /*判断转加密标志*/
        /*获取上传pin值*/
        String pinBlock = posAcctBalanceQueryRequest.getPin();
        /*判断是否为空*/
        if (null != pinBlock && "Y".equals(txnInfo.getSrcTxnAuthCfg().getPinFlag())) {
            //转pin
            newPin = xmlTreeUtil.getXmlTreeStringValue(McpsTreeNodeConstant.PIN_DATA);
        } else {
            rglog.error("上送密码为空，拒绝交易");
            throw new BizException(RespCodeEnum.POS_PIN_FORMAT_ERR.getRespCode(), RespCodeEnum.POS_PIN_FORMAT_ERR.getRespDesc());
        }
        /*获取基本商户信息*/
        MchntInfo mchntInfo = mchntService.getMchntInfo(instId, mchntNo);
        if (null == mchntInfo) {
            rglog.error("查询商户基本信息失败<{}>", mchntNo);
            throw new BizException(RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespCode(), RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespDesc());
        }
        /*初始化dubbo服务*/
        DubboService dubboService = new DubboServiceImpl();
        /*本行借记卡*/
        if (McpsAcctTypeEnum.OWN_DEBIT.getAcctType().equals(acctAndFeeType.getAcctType()) ||
                McpsAcctTypeEnum.OWN_CREDIT.getAcctType().equals(acctAndFeeType.getAcctType())) {
            /*初始化银行卡余额查询请求*/
            //TODO 调用核心余额查询接口,由项目组实现
        } else if (McpsAcctTypeEnum.OTHER_DEBIT.getAcctType().equals(acctAndFeeType.getAcctType()) ||
                McpsAcctTypeEnum.OTHER_CREDIT.getAcctType().equals(acctAndFeeType.getAcctType())) {
            /*初始化银行卡余额查询请求*/
            AcctBalanceQueryRequest acctBalanceQueryRequest = new AcctBalanceQueryRequest();
            /*设置报文头*/
            cc.rengu.igas.channel.cups.facade.base.Header header = new cc.rengu.igas.channel.cups.facade.base.Header();
            BeanUtil.beanCopy(posAcctBalanceQueryRequest.getHeader(), header);
            header.setTxnNum("02003000");
            String traceNo = xmlTreeUtil.getXmlTreeStringValue(McpsTreeNodeConstant.SYS_SEQ_NUM).substring(26);
            header.setTraceNo(traceNo);
            acctBalanceQueryRequest.setHeader(header);
            String acqInstCode = posParamDealService.genCupsAcqInstCode(instId, posAcctBalanceQueryRequest.getMchntNo());
            String fwdInstCode = XmlConfigUtil.getXmlConfigCacheKeyValue(CupsConfigConstant.CUPS_CONF_NODE, CupsConfigConstant.CUPS_FWD_INS_CODE);
            /*设置属性值*/
            String txnDate = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TXN_DATE);
            String txnTime = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TXN_TIME);
            acctBalanceQueryRequest.setCupsTraceNo(sysNum.substring(sysNum.length() - 6));
            acctBalanceQueryRequest.setTransDateTime(txnDate.substring(4, 8) + txnTime);
            acctBalanceQueryRequest.setReferenceNo(posParamDealService.getRefNo());
            acctBalanceQueryRequest.setMchntNo(mchntInfo.getCupsMchntNo());
            acctBalanceQueryRequest.setCupsMchntNo(mchntInfo.getCupsMchntNo());
            acctBalanceQueryRequest.setTermNo(termNo);
            acctBalanceQueryRequest.setMchntShortName(mchntInfo.getMchntSimpleName());
            acctBalanceQueryRequest.setMchntType(mchntInfo.getIndustryType());
            acctBalanceQueryRequest.setAcqInstCode(acqInstCode);
            acctBalanceQueryRequest.setFwdInstCode(fwdInstCode);
            acctBalanceQueryRequest.setOrderCcy(McpsParamConstant.INNER_DEFAULT_ORDERCCY);
            acctBalanceQueryRequest.setPayAcctNo(posAcctBalanceQueryRequest.getPayAcctNo());
            acctBalanceQueryRequest.setPinData(newPin);
            acctBalanceQueryRequest.setTrack2Data(posAcctBalanceQueryRequest.getTrack2Data());
            acctBalanceQueryRequest.setTrack3Data(posAcctBalanceQueryRequest.getTrack3Data());
            acctBalanceQueryRequest.setEntryMode(posAcctBalanceQueryRequest.getEntryMode());
            acctBalanceQueryRequest.setCardSeqNo(posAcctBalanceQueryRequest.getCardSeqNo());
            acctBalanceQueryRequest.setIcConCode(posAcctBalanceQueryRequest.getIcConCode());
            acctBalanceQueryRequest.setIcData(posAcctBalanceQueryRequest.getIcData());
            /*初始化终端信息*/
            CupsTermInfo cupsTermInfo = new CupsTermInfo();
            /*设置属性值*/
            cupsTermInfo.setLatitude(posAcctBalanceQueryRequest.getTermInfo().getLatitude());
            cupsTermInfo.setLongitude(posAcctBalanceQueryRequest.getTermInfo().getLongitude());
            cupsTermInfo.setNetworkLicense(posAcctBalanceQueryRequest.getTermInfo().getNetworkLicense());
            cupsTermInfo.setDeviceType(posAcctBalanceQueryRequest.getTermInfo().getDeviceType());
            cupsTermInfo.setSerialNum(posAcctBalanceQueryRequest.getTermInfo().getSerialNum());
            cupsTermInfo.setEncryptRandNum(posAcctBalanceQueryRequest.getTermInfo().getEncryptRandNum());
            cupsTermInfo.setSecretText(posAcctBalanceQueryRequest.getTermInfo().getSecretText());
            cupsTermInfo.setAppVersion(posAcctBalanceQueryRequest.getTermInfo().getAppVersion());
            acctBalanceQueryRequest.setTermInfo(cupsTermInfo);
            if (StringUtil.isEmptyOrNull(cupsTermInfo.getDeviceType())) {
                acctBalanceQueryRequest.setTermType(mchntTermInfo.getTermType());
            } else {
                acctBalanceQueryRequest.setTermType(cupsTermInfo.getDeviceType());
            }
            acctBalanceQueryRequest.setTermRead(posAcctBalanceQueryRequest.getTermRead());
            rglog.debug("他行借记卡查询请求报文<{}>", JSON.toJSONString(acctBalanceQueryRequest));
            /*服务调用*/
            cc.rengu.igas.channel.cups.facade.result.Result<AcctBalanceQueryResponse> result = (cc.rengu.igas.channel.cups.facade.result.Result<AcctBalanceQueryResponse>) dubboService.callDubboService("cupsPayService", "acctBalanceQuery", acctBalanceQueryRequest);
            /*失败处理*/
            if (null == result || null == result.getResult() || (!result.getResult().getRespCode().equals(McpsParamConstant.DUBBO_SUCCESS))) {
                rglog.error("查询银行卡余额失败");
                //throw new BizException(RespCodeEnum.QUERY_ERROR.getRespCode(),RespCodeEnum.QUERY_ERROR.getRespDesc());
                /*设置返回码 返回信息*/
                if (null == result || !result.isSuccess()) {
                    posAcctBalanceQueryResponse.setRespCode(OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespCode());
                    posAcctBalanceQueryResponse.setRespDesc(OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespDesc());
                    bizResponse.setRespCode(OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespCode());
                    bizResponse.setRespDesc(OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespDesc());
                } else {
                    posAcctBalanceQueryResponse.setRespCode(result.getResult().getRespCode());
                    posAcctBalanceQueryResponse.setRespDesc(result.getResult().getRespDesc());
                    posAcctBalanceQueryResponse.setIcData(result.getResult().getIcData());
                    bizResponse.setRespCode(result.getResult().getRespCode());
                    bizResponse.setRespDesc(result.getResult().getRespDesc());
                }
            } else {
                /*获得余额*/
                String cupsAcctBalance = result.getResult().getAcctBalance();
                String balType1 = cupsAcctBalance.substring(2, 4);
                String balType2 = cupsAcctBalance.substring(22, 24);
                String ledgerBalFlag = "";
                String ledgerBal = "";
                String adsBalFlag = "";
                String adsBal = "";

                if ("01".equals(balType1)) {
                    ledgerBalFlag = cupsAcctBalance.substring(7, 8);
                    ledgerBal = cupsAcctBalance.substring(8, 20);
                } else if ("02".equals(balType1)) {
                    adsBalFlag = cupsAcctBalance.substring(7, 8);
                    adsBal = cupsAcctBalance.substring(8, 20);
                }
                if ("01".equals(balType2)) {
                    ledgerBalFlag = cupsAcctBalance.substring(27, 28);
                    ledgerBal = cupsAcctBalance.substring(28, 40);
                } else if ("02".equals(balType2)) {
                    adsBalFlag = cupsAcctBalance.substring(27, 28);
                    adsBal = cupsAcctBalance.substring(28, 40);
                }

                balance = AmountUtil.changeF2Y(ledgerBal);
                BalanceInfo balanceInfo = new BalanceInfo();
                balanceInfo.setAcctType(balType2);
                balanceInfo.setBalance(balance);
                balanceInfo.setBalanceCcy("156");
                balanceInfo.setBalanceSign(adsBalFlag);
                posAcctBalanceQueryResponse.setBalanceInfo(balanceInfo);

                /*获得ic卡数据域*/
                posAcctBalanceQueryResponse.setIcData(result.getResult().getIcData());
                bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
                bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
            }
        } else {
            bizResponse.setRespCode(RespCodeEnum.NOT_SURPPORT_CREDIT_QUERY.getRespCode());
            bizResponse.setRespDesc(RespCodeEnum.NOT_SURPPORT_CREDIT_QUERY.getRespDesc());
        }
        /*重组报文*/
        posAcctBalanceQueryResponse.setHeader(posAcctBalanceQueryRequest.getHeader());
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setResult(posAcctBalanceQueryResponse);
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        PosAcctBalanceQueryResponse posAcctBalanceQueryResponse = (PosAcctBalanceQueryResponse) bizResponse.getResult();
        posAcctBalanceQueryResponse.setRespCode(bizResponse.getRespCode());
        posAcctBalanceQueryResponse.setRespDesc(bizResponse.getRespDesc());
        ConvertUtil.convertInput(posAcctBalanceQueryResponse);
    }
}
